package com.runjian.rundo.iot.agent.iec104.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.ListUtil;
import com.runjian.rundo.iot.agent.common.message.DeviceMessage;
import org.springframework.stereotype.Component;

import com.runjian.rundo.iot.agent.iec104.consts.Action;
import com.runjian.rundo.iot.agent.iec104.session.Iec104TcpClientDeviceSession;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 动作执行管理器
 *
 * @author CaoQingHua
 *
 */
@Slf4j
@Component
public class ActionHandleManager {

    private Map<Action, AbstractActionHandle> actionHandleMap = new HashMap<>();

    public ActionHandleManager(List<AbstractActionHandle> actionHandleList) {
        actionHandleList.forEach(actionHandle -> actionHandleMap.put(actionHandle.getAction(), actionHandle));
    }

    public void handleAction(Iec104TcpClientDeviceSession iec104DeviceSession,DeviceMessage deviceMessage, List<Action> actions, String... deviceIds) {
        if (ObjectUtil.isEmpty(actions)) {
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug("执行动作,动作集:{}", actions);
        }
        actions.forEach(action -> {
            AbstractActionHandle abstractActionHandle = this.actionHandleMap.get(action);
            if (null == abstractActionHandle) {
                if (log.isDebugEnabled()) {
                    log.debug("当前动作片时程序不存在,动作:{}", action);
                }
                return;
            }
            // 处理程序
            abstractActionHandle.handle(deviceMessage,iec104DeviceSession);
        });
    }

    public void handleAction(Iec104TcpClientDeviceSession iec104DeviceSession,DeviceMessage deviceMessage, Action... actions) {
        if (ObjectUtil.isEmpty(actions)) {
            return;
        }
        this.handleAction(iec104DeviceSession,deviceMessage, ListUtil.of(actions));
    }

}
